package com.example.demo.service.impl;

import com.example.demo.entity.Compression;
import com.example.demo.mapper.CompressionMapper;
import com.example.demo.service.DataCompressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xerial.snappy.Snappy;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Date;

/**
 * @Description
 * @Author chenhuiyu
 * @Date 2023/12/18
 */
@Service
public class DataCompressServiceImpl implements DataCompressService {
    @Autowired
    private CompressionMapper compressionMapper;

    @Override
    public void dataCompress(Compression compression) {
        try {
            byte[] buffer = Snappy.compress(compression.getData());
            compression.setCompressData(Arrays.toString(buffer));
            compression.setCreateTime(new Date());
            compressionMapper.insertCompression(compression);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public String readData(Integer id) {
        Compression compression = compressionMapper.selectData(id);
        String str = compression.getCompressData().replace("[", "");
        String replace = str.replace("]", "");
        String[] split = replace.split(",");
        byte[] bytes = new byte[split.length];
        int i = 0;
        for (String s : split) {
            bytes[i] = Byte.parseByte(s.trim());
            i++;
        }
        System.out.println(Arrays.toString(bytes));
        try {
            byte[] buffer = Snappy.uncompress(bytes);
            System.out.println(Arrays.toString(buffer));
            return new String(buffer, StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
